/*
 *newest
 *
 *
 * */

#include "client.h"
#define MAXSIZE 1000

void getsCommand(client_task_t * task){
    int clientfd=task->peerfd;
    char *filename=task->train.buff;
    off_t length=0;
    
    printf("filename:%s\n",filename);
    train_t t;


    //打开文件
    int fd=open(filename,O_RDWR|O_CREAT|O_APPEND,0644);
    if(fd==-1){
        perror("fopen");
    }
    printf("open %s success\n",filename);

    //获取文件长度
    int ret=recvn(clientfd,&length,sizeof(length));
    if(ret==0){
        printf("recvn failed\n");
    }
    printf("file length %ld\n",length);
    
    //断点续传
    struct stat st;
    memset(&st,0,sizeof(st));
    fstat(fd,&st);
    printf("length:%ld,st.st_size:%ld\n",length,st.st_size);
    length-=st.st_size;
    send(clientfd,&st.st_size,sizeof(st.st_size),0);
    lseek(fd,st.st_size,SEEK_SET);

    //根据文件长度确定接收的方式
    off_t threshold =100*1024*1024;
    if(length<threshold){
        //小文件传输
        printf("send smell file\n");
        memset(t.buff,0,sizeof(t.buff));
            //接收确定个字节的数据
    int left = length;
    char* pbuf =t.buff;
    int ret = 0;
    while (left > 0) {
        memset(t.buff,0,sizeof(t));
        //先接文件长度
        recv(clientfd,&t.len,4,MSG_WAITALL);
        //再接文件内容
        ret = recv(clientfd, t.buff, t.len, MSG_WAITALL);
        if (ret < 0) {
            perror("recv");
            break;
        } else if (ret == 0) {
            break;
        }

        ret=write(fd,t.buff,t.len);
        printf("ret:%d\n",ret);
        printf("write success\n");
        pbuf += ret;
        left -= ret;
    }

        close(fd);
        printf("gets %s success\n",filename);
        return;
    }else{
        printf("send big file\n");
        //接收大文件
        ftruncate(fd,length);
        char* pMap = (char*)mmap(NULL, 
            length, PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
        if (pMap) {
        int ret = recv(task->peerfd, pMap, 
                       length,MSG_WAITALL);
         printf("ret: %d\n", ret);
         }
        printf("gets %s success\n",filename);
    }

}
